package com.stylefeng.guns.modular.huamao.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;
@SuppressWarnings("all")
@Controller
@CrossOrigin
@RequestMapping("/app")
public class AppAgentsController extends BaseController {
	@Autowired
	private ILogScoreService iLogScoreService;
    @Autowired
    private CacheUtil cacheUtil;
	@Autowired
	private IAdsService iAdsService;
	@Autowired
	private ISktShopsService iSktShopsService;
	@Autowired
    private ISktOrdersStoresService sktOrdersStoresService;
	@Autowired
    private IAppAgentsApplysService iAppAgentsApplysService;
	@Autowired
    private IAppAgentsService iAppAgentsService;
	@Autowired
    private IAppUserService iAppUserService;
	@Autowired
	private IUsersDrawsService iUsersDrawsService;
	@Autowired
    private IAppAgentsStockholderService iAppAgentsStockholderService;
	@Autowired
    private IAppSktAreaService iAppSktAreaService;
//	@Autowired
//	private
	/**
     * 代理商分红记录
     * @param code
     * @return
     */
    @RequestMapping("/Agents/dividendRecord")
    @ResponseBody
    public AppResult getArticle(@ModelAttribute("pageIndex")String pageIndex){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Map<String, Object> map = new HashMap<>();
            map.put("userId",user.getUserId());
            map.put("page",MSGUtil.isBlank(pageIndex)?(1-1)*10:(Integer.parseInt(pageIndex)-1)*10);
            map.put("pageNum",10);
            List<Map<String,Object>> list = iLogScoreService.selectLogScoreByUserId(map);
            List<Object> objects = new ArrayList<>();
            for (Map<String,Object> maps:list){
                maps.put("orderNo",maps.get("orderNo"));
                maps.put("score",maps.get("score").toString());
                maps.put("remark",maps.get("remark"));
                maps.put("createTime",maps.get("createTime"));
                objects.add(maps);
            }
            return AppResult.OK("查询成功",objects);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("查询失败",-2);
        }

    }  
    
//    /**
//     * 引导页面
//     */
//    @RequestMapping("/Site/welcome")
//    @ResponseBody
//    public AppResult siteWelcome(@ModelAttribute(value="position") Integer positionId,@ModelAttribute(value="num")Integer num){
//    	List<Map<String,Object>> list = iAdsService.siteWelcome(positionId,num);
//    	return AppResult.OK(list);
//    }
    /**
     * 线下商家主页
     */
    @RequestMapping("/shops/store")
    @ResponseBody
    public AppResult shopsStore(@ModelAttribute(value="shopId") Integer shopId){
    	Map<String,Object> map = new HashMap<String, Object>();
    	map = iSktShopsService.shopsStore(shopId);
        return AppResult.OK("查询成功",map);
    } 
    /**
     * 周边主页（包括商家名称搜索,点击行业搜索）
     */
    @RequestMapping("/shops/storePos")
    @ResponseBody
    public AppResult shopsStorePos(@ModelAttribute(value="lng") BigDecimal lng,
    		@ModelAttribute(value="lat") BigDecimal lat,
    		@ModelAttribute(value="shopName") String shopName,
    		@ModelAttribute(value="industry") String industry){
    	List<Map<String,Object>> list = iSktShopsService.shopsStorePos(lng,lat,shopName,industry);
    	if (list==null||list.size()<1){
            list=new ArrayList<>();
        }
        return AppResult.OK("查询成功",list);
    }
    /**
     * 根据经纬度查询
     * @param lng
     * @param lat
     * @param pageIndex
     * @return
     */
    @RequestMapping("/shops/storePosL")
    @ResponseBody
    public AppResult shopsStorePosL(@ModelAttribute(value="lng") BigDecimal lng,
    		@ModelAttribute(value="lat") BigDecimal lat,
    		@ModelAttribute("pageIndex") Integer pageIndex){
    	PageHelper.startPage(pageIndex, 10);
    	List<Map<String,Object>> list = iSktShopsService.shopsStorePosL(lng,lat);
    	PageInfo page = new PageInfo<>(list);
    	JSONObject json = new JSONObject();
    	 if (list!=null && list.size()>0){
             json.put("tatolPage",page.getPages());
             json.put("maps",list);
         }else{
             json.put("tatolPage",1);
             json.put("maps","");
         }
        return AppResult.OK("查询成功",json);
    }


    /**
     * 申请积分
     * @param shopId 该店铺商家ID
     * @param payMoney 支付金额
     * @param scoreRatio 积分比例
     * @return
     */
    @RequestMapping("/score/orderStore")
    @ResponseBody
    public AppResult orderStore(@ModelAttribute(value="shopId") Integer shopId,@ModelAttribute(value="payMoney") BigDecimal payMoney,@ModelAttribute(value="scoreRatio") Integer scoreRatio){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Users users = iAppUserService.selectUsersByUserId(user.getUserId());
            if (users.getIsOperation()!=1){
                return AppResult.ERROR("该功能已关闭",-1);
            }
            Map<String,Object> usersShop=iSktShopsService.selectUsersByShopId(shopId);
            if (Integer.parseInt(usersShop.get("isOperation").toString())!=1){
                return AppResult.ERROR("该商家无法赠送积分",-1);
            }
            if(user==null){
              return AppResult.ERROR("您未登录",-2);
          }
            Map<String, Object> map = sktOrdersStoresService.apporderStore(shopId, payMoney, scoreRatio, user.getUserId());
            String mes = (String) map.get("mes");
            if (mes != null && mes != "") {
                return AppResult.ERROR(mes);
            }
            return AppResult.OK("申请成功！", map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("申请失败");
        }
    }

    /**
     * 申请代理
     * @return
     */
    @RequestMapping("/agents/account")
    @ResponseBody
    public AppResult account(){
        try {
          Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
          if(user==null){
              return AppResult.ERROR("您未登录",-2);
          }
            Users users = new Users();
            users.setUserId(user.getUserId());
            Users users1 = iAppUserService.selectById(users);
            Map<Object, Object> map = new HashMap<>();
            map.put("userPhone",users1.getUserPhone());
            return  AppResult.OK("查询成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("失败",-2);
        }
    }
    /**
     * 用户提现
     * @return
     */
    @RequestMapping("/users/userOrders")
    @ResponseBody
    public AppResult userOrders(@ModelAttribute(value="pageIndex") Integer pageIndex){
      Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
      if(user==null){
          return AppResult.ERROR("您未登录",-2);
      }
    	 Page<UsersDraws> page = new Page<UsersDraws>(pageIndex,50);
    	 EntityWrapper<UsersDraws> en = new EntityWrapper<UsersDraws>();
    	 en.where("userId", user.getUserId()).orderBy("checkTime", false);
    	 //en.where("userId", 1).orderBy("checkTime", false);
    	 Page<UsersDraws> users = iUsersDrawsService.selectPage(page,en);
        JSONObject json=new JSONObject();
        if (users!=null && users.getSize()>0){
            json.put("tatolPage",users.getPages());
            json.put("maps",users.getRecords());
        }else{
            json.put("tatolPage",1);
            json.put("maps","");
        }
    	 return AppResult.OK(json);
    }

    /**
     * 代理级别
     * @return
     */
    @RequestMapping("/agents/proxyLevel")
    @ResponseBody
    public AppResult proxyLevel(){
        List<Object> list = new ArrayList<>();
        Map<Object, Object> map = new HashMap<>();
        map.put("id",10);
        map.put("name","省代");
        list.add(map);
        Map<Object, Object> maps = new HashMap<>();
        maps.put("id",11);
        maps.put("name","市代");
        list.add(maps);
        Map<Object, Object> mapes = new HashMap<>();
        mapes.put("id",12);
        mapes.put("name","区县代");
        list.add(mapes);
        return AppResult.OK("查询成功",list);
    }

    /**
     * 股东职位
     * @return
     */
    @RequestMapping("/agents/position")
    @ResponseBody
    public AppResult position(){
        List<Object> list = new ArrayList<>();
        Map<Object, Object> map = new HashMap<>();
        map.put("id",2);
        map.put("name","总裁");
        list.add(map);
        Map<Object, Object> maps = new HashMap<>();
        maps.put("id",3);
        maps.put("name","行政总监");
        list.add(maps);
        Map<Object, Object> mapes = new HashMap<>();
        mapes.put("id",4);
        mapes.put("name","财务总监");
        list.add(mapes);
        Map<Object, Object> mapes1 = new HashMap<>();
        mapes1.put("id",5);
        mapes1.put("name","部门经理");
        list.add(mapes1);
        Map<Object, Object> mapes2 = new HashMap<>();
        mapes2.put("id",7);
        mapes2.put("name","普通股东");
        list.add(mapes2);
        return AppResult.OK("查询成功",list);
    }

    /**
     * 提交申请
     * @param proxyLevel
     * @param position
     * @param area
     * @param account
     * @return
     */
    @RequestMapping("/agents/applicationAgency")
    @ResponseBody
    @Transactional
    public AppResult applicationAgency(@ModelAttribute("proxyLevel")String proxyLevel,
    								   @ModelAttribute("position")String position,
                                       @ModelAttribute("area")String area,
                                       @ModelAttribute("account")String account,
                                       @ModelAttribute("moneyOrderImg")String moneyOrderImg,
                                       @ModelAttribute("remark")String remark){
        try {
          Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
          if(user==null){
              return AppResult.ERROR("您未登录",-2);
          }
            int [] status={0,1,2,3};
            Map<String, Object> map = new HashMap<>();
            map.put("userId",user.getUserId());
            map.put("status",status);
            AgentsApplys hasApplys=iAppAgentsApplysService.selectAgentsApplysByUserIdAndStatus(map);
            if (!MSGUtil.isEmpty(hasApplys)){
                return AppResult.ERROR("你已提交过申请，正审核中不能继续申请",-1);
            }
            int [] statu={-1,-2};
            map.put("status",statu);
            AgentsApplys agentsApplys = iAppAgentsApplysService.selectAgentsApplysByUserIdAndStatus(map);//?
            Users users = iAppUserService.selectById(user);
            if (users.getUserType()<1){
                return AppResult.ERROR("必须升级为主管才能申请代理",-1);
            }
            if (!users.getUserPhone().equals(account)){
                return AppResult.ERROR("申请账号不正确",-1);
            }
            //判断代理级别
            //根据app传过来最后一级区域id查找出对应的省市级别id
            Integer proxyLevels = Integer.parseInt(proxyLevel);
            map.put("proxyLevel",proxyLevels);
            map.put("area",Integer.parseInt(area));
            SktAgents sktAgents=new SktAgents();
            if (proxyLevels==10){//省级
                //获取代理公司信息
                sktAgents=iAppAgentsService.selectAgentsProvinceId(map);
            }
            if (proxyLevels == 11) {//市级
                //获取代理公司信息
                sktAgents=iAppAgentsService.selectAgentsCityId(map);
            }
            if (proxyLevels==12){// 区县级
                //获取代理公司信息
                sktAgents=iAppAgentsService.selectAgentsAreaId(map);
            }
            //申请职位前，判断该职位是否还有
            Integer positions = Integer.parseInt(position);
            map.put("agentId",sktAgents.getAgentId());
            map.put("position",positions);
            if (positions==2 || positions==3 || positions==4){
                List<SktAgentsStockholder> sktAgentsStockholders=iAppAgentsStockholderService.selectAgentsStockholderList(map);
                if (sktAgentsStockholders.size()>0){
                    return AppResult.ERROR("该职位已存在，无法申请",-1);
                }
            }
            if (positions==5){
                List<SktAgentsStockholder> sktAgentsStockholders=iAppAgentsStockholderService.selectAgentsStockholderList(map);
                if (sktAgentsStockholders.size()>2){
                    return AppResult.ERROR("该职位已存在，无法申请",-1);
                }
            }
            int num=0;
            BigDecimal money = new BigDecimal(0.00);
            //根据申请的股东类型判断是否有剩余股份数量    股东类型 1董事长 2总裁(4股) 3行政总监(3股) 4财务总监(3股) 5部门经理(3个 2股) 6监事 7普通股东(1股) (1和6不存在)
            if (positions==2){//申请总裁，判断该职位是否已存在
                //判断股份是否足够
                if (sktAgents.getGPsurplusStockNum()<4){
                    return AppResult.ERROR("管理股东剩余股份数量不足",-1);
                }
                num=4;
                money=BigDecimal.valueOf(num*sktAgents.getAgencyFee());
            }else if(positions==3 || positions==4){//申请行政总监/财务总监
                //判断股份是否足够
                if (sktAgents.getGPsurplusStockNum()<3){
                    return AppResult.ERROR("管理股东剩余股份数量不足",-1);
                }
                num=3;
                money=BigDecimal.valueOf(num*sktAgents.getAgencyFee());
            }else if(positions==5){
                //判断股份是否足够
                if (sktAgents.getGPsurplusStockNum()<2){
                    return AppResult.ERROR("管理股东剩余股份数量不足",-1);
                }
                num=2;
                money=BigDecimal.valueOf(num*sktAgents.getAgencyFee());
            }else if (positions==7){
                //判断股份是否足够
                if (sktAgents.getGPsurplusStockNum()<1){
                    return AppResult.ERROR("管理股东剩余股份数量不足",-1);
                }
                num=1;
                money=BigDecimal.valueOf(num*sktAgents.getAgencyFee());
            }
            AgentsApplys agentsApplys1=new AgentsApplys();
            agentsApplys1.setOrderNo(StringUtils.getOrderIdByTime("4"));//申请代理公司股东单号
            agentsApplys1.setAgentId(sktAgents.getAgentId());//代理公司ID
            agentsApplys1.setUserId(users.getUserId());//用户ID
            agentsApplys1.setPhone(users.getUserPhone());//申请人手机号码
            agentsApplys1.setType(positions);//股东类型 1董事长 2总裁 3行政总监 4财务总监 5部门经理 6监事 7普通股东
            agentsApplys1.setStockNum(num);
            agentsApplys1.setMoney(money);
            agentsApplys1.setMoneyOrderImg(moneyOrderImg);
            agentsApplys1.setStatus(0);
            agentsApplys1.setRemark(remark);
            agentsApplys1.setCreateTime(new Date());
            
            
//            Map<String, Object> maps = new HashMap<>();
//            int [] status={1};
//            maps.put("userId",user.getUserId());
//            maps.put("status",status);
//            AgentsApplys agentsApplys = iAppAgentsApplysService.selectAgentsApplysByUserIdAndStatus(maps);
//            if (MSGUtil.isBlank(agentsApplys)){
//                return AppResult.ERROR("审核异常，不能打款",-1);
//            }
//            //插入股东申请记录
//            AgentsApplys agentsApplys1 = new AgentsApplys();
//            agentsApplys1.setMoneyOrderImg(moneyOrderImg);
//            agentsApplys1.setShaId(agentsApplys.getShaId());
//            agentsApplys1.setStatus(2);
//            agentsApplys1.setRemark(remark);
//            boolean b = iAppAgentsApplysService.updateById(agentsApplys1);
//            if (b){
//                return AppResult.OK("操作成功",null);
//            }
//            return AppResult.ERROR("操作失败",-1);
            
            
            if (MSGUtil.isEmpty(agentsApplys)){
                boolean insert = iAppAgentsApplysService.insert(agentsApplys1);
                if (insert){
                    return AppResult.OK("申请成功",null);
                }
            }else{
                agentsApplys1.setShaId(agentsApplys.getShaId());
                boolean b = iAppAgentsApplysService.updateById(agentsApplys1);
                if (b){
                    return AppResult.OK("申请成功",null);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("失败");
        }
        return AppResult.ERROR("申请失败",-1);
    }


    /**
     * 申请代理2
     * @return
     */
    @RequestMapping("/agents/checkApply")
    @ResponseBody
    @Transactional
    public AppResult checkApply(){
        try {
          Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
          if(user==null){
              return AppResult.ERROR("您未登录",-2);
          }
            Map<String,Object> map=iAppAgentsApplysService.selectAgentsAppLysCheckApplyByUserId(user.getUserId());
            if (MSGUtil.isBlank(map)){
                return AppResult.OK("查询成功",map);
            }
            int alevel = Integer.parseInt(map.get("alevel").toString());
            map.put("type", RemarksGenerate.position(Integer.parseInt(map.get("type").toString())));
            map.put("status",RemarksGenerate.status(Integer.parseInt(map.get("status").toString())));
            map.put("alevel",RemarksGenerate.alevel(Integer.parseInt(map.get("alevel").toString())));
            String areaName="";
            if (alevel==10){
                SktAreas sktAreas=iAppSktAreaService.selectAreaByProvinceId(Integer.parseInt(map.get("provinceId").toString()));
                areaName=sktAreas.getAreaName();
            }
            if (alevel==11){
                SktAreas sktAreas=iAppSktAreaService.selectAreaByCityId(Integer.parseInt(map.get("cityId").toString()));
                areaName=sktAreas.getAreaName();
            }
            if (alevel==12){
                SktAreas sktAreas=iAppSktAreaService.selectAreaByAreaId(Integer.parseInt(map.get("areaId").toString()));
                areaName=sktAreas.getAreaName();
            }
            map.put("areaName",areaName);
            return AppResult.OK("查询成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("查询失败",-1);
        }
    }

    /**
     * 确认打款
     * @param moneyOrderImg
     * @param remark
     * @return
     */
    @RequestMapping("/agents/confirmMoney")
    @ResponseBody
    public AppResult confirmMoney(@ModelAttribute("moneyOrderImg")String moneyOrderImg,@ModelAttribute("remark")String remark){
        try{
          Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
          if(user==null){
              return AppResult.ERROR("您未登录",-2);
          }
            Map<String, Object> maps = new HashMap<>();
            int [] status={1};
            maps.put("userId",user.getUserId());
            maps.put("status",status);
            AgentsApplys agentsApplys = iAppAgentsApplysService.selectAgentsApplysByUserIdAndStatus(maps);
            if (MSGUtil.isBlank(agentsApplys)){
                return AppResult.ERROR("审核异常，不能打款",-1);
            }
            //插入股东申请记录
            AgentsApplys agentsApplys1 = new AgentsApplys();
            agentsApplys1.setMoneyOrderImg(moneyOrderImg);
            agentsApplys1.setShaId(agentsApplys.getShaId());
            agentsApplys1.setStatus(2);
            agentsApplys1.setRemark(remark);
            boolean b = iAppAgentsApplysService.updateById(agentsApplys1);
            if (b){
                return AppResult.OK("操作成功",null);
            }
            return AppResult.ERROR("操作失败",-1);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("操作失败",-1);
        }

    }

}
